package com.kyk.filter;

import com.kyk.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class CustomAuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono< Void > filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断是否需要做用户鉴权，如果是则直接放行
        String path = exchange.getRequest().getURI().getPath();
        if (path.contains("/auth/login")||
                path.contains("/auth/logout")||
                path.contains("/auth/myinfo")||
                path.contains("auth/props")||
                path.contains("/index/index.html")||
                path.startsWith("/index/")){
            return chain.filter(exchange);
        }
        // 1. 实现你的过滤逻辑，例如获取请求头中的token并进行验证:cite[4]

        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
                try {
                    JwtUtil.parseJWT(token);
                    // 2.  token验证通过，放行请求到下一个过滤器或下游服务:cite[4]
                    return chain.filter(exchange);
                }catch (Exception e){
                    // continue
                }

        }

            // 3.  token验证失败，拦截请求并返回未授权状态码:cite[4]
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();

    }
    @Override
    public int getOrder() {
        // 4. 返回过滤器的执行顺序，值越小优先级越高:cite[3]:cite[5]
        return 0;
    }
}